package org.altoro.core.services.http;

import lombok.extern.slf4j.Slf4j;
import org.altoro.api.GrpcAPI;
import org.altoro.core.Wallet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
@Slf4j(topic = "API")
public class DelegateServlet extends RateLimiterServlet {

    @Autowired
    private Wallet wallet;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        try {
            boolean visible = Util.getVisible(request);
            GrpcAPI.DelegateList reply = wallet.getDelegateList();
            if (reply != null) {
                response.getWriter().println(JsonFormat.printToString(reply, visible));
            } else {
                response.getWriter().println("{}");
            }
        } catch (Exception e) {
            Util.processError(e, response);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        try {
            boolean visible = Util.getVisible(request);
            GrpcAPI.DelegateList reply = wallet.getDelegateList();
            if (reply != null) {
                response.getWriter().println(JsonFormat.printToString(reply, visible));
            } else {
                response.getWriter().println("{}");
            }
        } catch (Exception e) {
            Util.processError(e, response);
        }
    }
}
